package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishControllor {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清除缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1" ;
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    //菜品管理（起售停售）
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status, @RequestParam List<Long> ids) {
        Set key = redisTemplate.keys("dish_*");
        redisTemplate.delete(key);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        Dish dish = new Dish();
        //设置数据库中状态
        dish.setStatus(status);
        lqw.in(Dish::getId, ids);
        dishService.update(dish, lqw);
        return R.success("修改成功");
    }

    //删除，批量删除
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        dishService.delete(ids);
        //清除缓存
        Set key = redisTemplate.keys("dish_*");
        redisTemplate.delete(key);
        return R.success("删除成功");
    }


    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        String key="dish_" + page + "_" + pageSize+'_'+name;
        Page<DishDto> resultPage= (Page<DishDto>) redisTemplate.opsForValue().get(key);
        if(resultPage!=null){
            return R.success(resultPage);
        }
        //分页
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //模糊查询
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询
        dishService.page(pageInfo, lqw);
        //要返回的结果，包括分类名称
         resultPage = new Page<>();
        //把pageInfo数据拷贝到resultPage中
        BeanUtils.copyProperties(pageInfo, resultPage, "records");
        //从数据库中查询到的集合，不包含分类名称
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> resultlist = new ArrayList<>();

        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record, dishDto);
            //设置分类的名称
            Category category = categoryService.getById(record.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            resultlist.add(dishDto);
        }
        resultPage.setRecords(resultlist);
        redisTemplate.opsForValue().set(key,resultPage,24,TimeUnit.MINUTES);
        return R.success(resultPage);
    }

    //根据id查询菜品信息和口味信息
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavlor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //清除缓存
        Set key=redisTemplate.keys("dish_*") ;
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }

    //套餐管理中添加套餐新增菜品
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //先进行redis查询，
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        List<DishDto> resultLiset = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果redsis中存在就直接返回
        if (resultLiset != null) {
            return R.success(resultLiset);
        }
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //根据菜品名称模糊查询
        lqw.like(StringUtils.isNotEmpty(dish.getName()), Dish::getName, dish.getName());
        //根据分类ID精确查询
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //根据售卖情况查询（查询起售状态）
        lqw.eq(Dish::getStatus, 1);
        //排序，根据SORT正序排序，在根据修改时间倒叙排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询
        List<Dish> list = dishService.list(lqw);

        resultLiset = list.stream().map(dishItem -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dishItem, dishDto);
            //查询菜品口味
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dishItem.getId());
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(list1);
            return dishDto;
        }).collect(Collectors.toList());
        //如果没有就查询数据库，从数据库查询的信息存入到redis中
        redisTemplate.opsForValue().set(key, resultLiset, 24, TimeUnit.HOURS);
        return R.success(resultLiset);

    }


}
